#coding: utf8
import re
import os.path
from pygeocoder import Geocoder
import datetime
from utils import Utils
from FourSqrMasterDB import FourSqrMasterDB
from FourSqrUtils import FourSqrUtils
from items import RestaurantItem
from items import RestaurantReview
import time
import foursquare
import sys
import logging


class fourSquareHist(object):

    my_secret='2DPOKZJJ3RSRRAMP3HFT13R5VP5UC0ZRQXEKNWQTEZUPTBYZ'
    my_id='5QXT2UX0VNBUADIOK2G0WUVKM314PH1W50ZHASHICTPC1MPU'
    

    db = None
    utils = None
    fourSqrUtils = None
    logLocalName="FOURSQR_HIST"

    
    def init(self):
        try:

            reload(sys)
            sys.setdefaultencoding('utf-8')
            
            self.db = FourSqrMasterDB()
            self.utils = Utils()
            self.db.utils=self.utils
            self.fourSqrUtils=FourSqrUtils()
            self.fourSqrUtils.utils=self.utils
            
            
            time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            filename = time + '.log'
            filename = os.path.join('../logFourSqrHist/',filename)
            self.utils.logProcessInit(filename)
            self.utils.logProcessBegin(self.logLocalName)

            """
            loghandler = logging.StreamHandler(stream=sys.stdout)
            foursquare.log.addHandler(loghandler)
            foursquare.log.setLevel(logging.DEBUG)
            """

       
            self.db.connectDB()

        except Exception,e:
            self.utils.logProcessDetail("Error fatal al init de fourSquareHist:  " + str(e), self.utils.ERROR)

    def run(self):
        try:
            #connect to foursquare
            client = foursquare.Foursquare(client_id=self.my_id, client_secret=self.my_secret)
            if client is not None:
                #list[0]: DS_URL_FOURSQUARE, list[1]: ID_REST_SOURCE
                list = self.db.getRestaurantsList()
                for i in list:
                    restaurant = RestaurantItem()
                    restaurant['id_venue'] = str(i[0])
                    restaurant['idRestSource'] = str(i[1])
                    self.fourSqrUtils.fillRestaurant(client,restaurant)
                    self.fourSqrUtils.fillRestaurantComments(client,restaurant)
                    self.db.insertRestaurants(restaurant,self.db.UPDATE)
                #self.utils.logProcessDetail("Restaurant: "+str(restaurant), self.utils.INFO)
            else:
                self.utils.logProcessDetail("can not connect to foursquare client is null", self.utils.ERROR)
                

        except Exception,e:
            self.utils.logProcessDetail("Error en run:  " + str(e), self.utils.ERROR)
        finally:
            self.utils.logProcessEnd("Finished", self.utils.DEBUG)
    
    
#foursquare is not a spider it calls 4sqr API
def main():
    try:
        fsq = fourSquareHist()
        fsq.init()
        fsq.run()
    except Exception,e:
        print "exception fatal: "+str(e)

    return True





if __name__ == "__main__":
    main()  